const base64 = require('./base64.js'); //Base64,hmac,sha1,crypto相关算法
const Crypto = require('./crypto.js');
require('./sha1.js');
require('./hmac.js');
import {
	Decrypt2
} from '@/common/aliyun_oss/secret.js'

import {
	initOssSTS
} from '@/common/api/index_api.js'

import {
	showToast
} from '@/common/utils/util.js'

const uploadFileSize = 1024 * 1024 * 1000; //  // 设置上传文件的大小限制,1000mb

export default {
	//初始化oss临时token
	uploadFile(filePath, successc, failc, fileType) {
		initOssSTS({
			platformCode: 'wanxinpsychology'
		}).then(res => {
			if (res.data.code == 200) {
				let stsInfo = JSON.parse(Decrypt2(res.data.data));
				console.log(stsInfo, "+++++++++++==")
				this.uploadFileData(filePath, stsInfo, successc, failc, fileType);
			} else {
				showToast(res.data.message);
			}
		})
	},
	/*
	 *上传文件到阿里云oss
	 *@param - filePath :图片的本地资源路径
	 *@param - dir:表示要传到哪个目录下
	 *@param - stsInfo:上传配置信息
	 *@param - successc:成功回调
	 *@param - failc:失败回调
	 @fileType -文件类型需要主动传递  img  audio  video 
	 */
	uploadFileData(filePath, stsInfo, successc, failc, fileType) {
		// if (!filePath || filePath.length < 9) {
		// 	wx.showModal({
		// 		title: '图片错误',
		// 		content: '请重试',
		// 		showCancel: false,
		// 	})
		// 	return;
		// }
		let suffix = filePath.split('.').pop().toLowerCase(); //非H5用此方法判断文件类型
		//图片名字 可以自行定义，     这里是采用当前的时间戳 + 150内的随机数来给图片命名的
		let dir = '';
		stsInfo.clientUserUpload.forEach((item, index) => {
			console.log(item.fileType);
			if (fileType == item.fileType) {
				dir = item.path;
			}
		})
		let filename = dir + '/' + new Date().getTime() + Math.floor(Math.random() * 150) + Math.random().toString(36)
			.substring(3, 20) + '.png'; //+ suffix
		let aliyunServerURL = stsInfo.uploadUrl; //OSS地址，需要https
		let policyBase64 = this.getPolicyBase64();
		let signature = this.getSignature(policyBase64, stsInfo); //获取签名

		uni.uploadFile({
			url: aliyunServerURL, //开发者服务器 url
			filePath: filePath, //要上传文件资源的路径
			name: 'file', //必须填file
			formData: {
				'key': filename,
				'policy': policyBase64,
				'OSSAccessKeyId': stsInfo.accessKeyId,
				'signature': signature,
				'x-oss-security-token': stsInfo.securityToken,
				'success_action_status': '200'
			},
			success: function(res) {
				if (res.statusCode != 200) {
					failc(new Error('上传错误:' + JSON.stringify(res)))
					return;
				}
				successc(stsInfo.imgAccessPrefix + "/" + filename);
			},
			fail: function(err) {
				err.wxaddinfo = aliyunServerURL;
				failc(err);
			}
		})
	},
	getPolicyBase64() {
		let date = new Date();
		date.setHours(date.getHours() + 1);
		let srcT = date.toISOString();
		const policyText = {
			"expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
			"conditions": [
				["content-length-range", 0, uploadFileSize]
			]
		};

		const policyBase64 = base64.encode(JSON.stringify(policyText));
		return policyBase64;
	},

	getSignature(policyBase64, stsInfo) {
		const accesskey = stsInfo.accessKeySecret;

		const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
			asBytes: true
		});
		const signature = Crypto.util.bytesToBase64(bytes);
		return signature;
		// return crypto.enc.Base64.stringify(crypto.HmacSHA1(policyBase64, accesskey));
	},

	getSuffix(filename) {
		let pos = filename.lastIndexOf('.')
		let suffix = ''
		if (pos != -1) {
			suffix = filename.substring(pos)
		}
		return suffix;
	},
	getFileName(filename) {
		console.log('filename:', filename)
		return 'sangfor/' + new Date().getTime() + Math.random().toString(36).substring(3, 20) + this._getSuffix(
			filename)
	},
	getImage(countPhoto) {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: countPhoto || 1, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album', 'camera'],
				camera: 'back',
				success: (res) => {
					resolve(res)
				}
			})
		});
	},
	getVideo() {
		return new Promise((resolve, reject) => {
			uni.chooseVideo({
				count: 1,
				camera: 'back',
				sourceType: ['album', 'camera'],
				compressed: false,
				success: function(res) {
					if (res.duration > 120) {
						showToast('视频时长超过上传限制：120S');
						return;
					}
					// if (res.size > uploadFileSize) {
					// 	uni.showToast({
					// 		title: '文件大小超过系统上传限制：' + uploadFileSize,
					// 		icon: 'none',
					// 		duration: 1000
					// 	});
					// 	return;
					// }
					resolve(res)
				},
				fail: () => {
					showToast('取消选择视频');
				}
			})
		});
	}
}
